package com.liu.manag.granter;

import com.liu.manag.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public abstract class AbstractUserTokenGranter  extends AbstractTokenGranter {
    protected AbstractUserTokenGranter( AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        User user = getUser(parameters);
        if(user == null){
            throw new InvalidGrantException("无法获取用户信息");
        }
        Authentication userAuth = new UsernamePasswordAuthenticationToken(user,user.getPassword(),user.getAuthorities());

        Map<String,String> userDetails = new HashMap<>();
        userDetails.put("id",user.getId().toString());
        userDetails.put("email",user.getEmail());
        userDetails.put("name",user.getUsername());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user,user.getPassword(),user.getAuthorities());
        usernamePasswordAuthenticationToken.setDetails(userDetails);



        OAuth2Request storeOauthRequest = getRequestFactory().createOAuth2Request(client,tokenRequest);
        OAuth2Authentication oAuth2Authentication =  new OAuth2Authentication(storeOauthRequest,usernamePasswordAuthenticationToken);
        return oAuth2Authentication;

    }

    protected abstract User getUser(Map<String, String> parameters);
}
